<template>
    <div class="app-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="成绩录入" name="first">
                <el-form ref="form" :rules="rules" :model="examScoreTable" :inline="true" label-width="80px">
                    <el-form-item label="班级" prop="classId" ref="classOption">
                        <el-select @change="classChange" v-model="examScoreTable.classId" clearable filterable
                            style="width:100%">
                            <el-option v-for="item in classOptions" :label="item.className" placeholder="选择班级"
                                :value="item.id" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="考试科目" prop="subjectId" ref="subjectOption">
                        <el-select @change="handleChange" v-model="examScoreTable.subjectId" clearable filterable
                            style="width:100%">
                            <el-option v-for="item in subjectOptions" :label="item.subjectName" placeholder="选择考试计划"
                                :value="item.subjectId" :key="item.subjectId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="考试计划" prop="examPlanId" ref="examPlanOption">
                        <el-select @change="handleChange" v-model="examScoreTable.examPlanId" clearable filterable
                            style="width:100%">
                            <el-option v-for="item in examOptions" :label="item.examName" placeholder="选择考试计划"
                                :value="item.id" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="mini" @click="submitForm">提交成绩</el-button>
                    </el-form-item>
                    <el-table v-if="examScoreTable.classId != null" :data="examScoreTable.examScoreList">
                        <el-table-column label="序号" align="center" type="index" />
                        <el-table-column label="学生ID" align="center" prop="studentId" :show-overflow-tooltip="true" />
                        <el-table-column label="学生姓名" align="center" prop="studentName" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <el-tooltip content="查看成绩" placement="top">
                                    <el-link type="primary" @click="openDialog(scope.row)">{{ scope.row.studentName }}<i
                                            class="el-icon-edit el-icon--right"></i>
                                    </el-link>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                        <el-table-column label="学号" align="center" prop="studentCode" :show-overflow-tooltip="true" />
                        <el-table-column label="班级" align="center" prop="className" :show-overflow-tooltip="true" />
                        <el-table-column label="成绩" align="center" prop="score" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <el-input type="number" v-model="scope.row.score" />
                            </template>
                        </el-table-column>
                        <el-table-column label="考试状态" align="center" prop="status" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.status" clearable filterable style="width:100%">
                                    <el-option v-for="item in statusOptions" :label="item.value" placeholder="请选择"
                                        :value="item.id" :key="item.id"></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div v-if="examScoreTable.classId == null" style="width: 100%;text-align: center;">
                        <font color="gray">请选择班级</font>
                    </div>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="数据导入" name="second">
                <div>
                    <!-- <el-button size="small" type="pain" @click="exportTemp" style="margin-bottom: 15px;">导出模板</el-button> -->
                    <div style="display: flex;">
                        <el-upload class="upload-demo" ref="upload" :action="activeUrl" :headers="upload.header"
                            :on-success="handleSuccess" :on-preview="handlePreview" :on-remove="handleRemove"
                            :file-list="fileList" :auto-upload="false" :limit="limit">
                            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                            <el-button style="margin-left:10px" size="small" type="success" @click="submitUpload">导入</el-button>
                        </el-upload>
                    </div>
                    <div style="line-height:2.0;font-family:Helvetica Neue">
                        <span style="color:red;margin-right:3px">*说明：</span>只能上传*.xls/xlsx文件,【
                        <el-tooltip content="导出模板" placement="top">
                            <span @click="exportTemp" style="color:blue"> 成绩导入模板 </span>
                        </el-tooltip>
                        】；学生姓名，班级，科目，考试等需要系统中存在且
                        <span style="color:red;">使用ID进行录入</span>，具体ID由系统中查看
                    </div>

                </div>
            </el-tab-pane>
        </el-tabs>

        <el-dialog title="查看成绩" :visible.sync="dialogVisible" width="30%">
            <div style="margin-bottom: 20px;">
                <font color="green">{{ this.studentName }}{{ this.examPlanName }}成绩</font>
            </div>
            <el-form ref="commentForm" :model="examComment" :inline="true" label-width="80px">
                <el-table :data="studentScore">
                    <el-table-column label="科目" align="center" prop="subjectName" />
                    <el-table-column label="分数" align="center" prop="score" />
                </el-table>
                <el-form-item label="评语" prop="comment" style="margin-top: 30px;">
                    <el-input type="textarea" :rows="2" style="width: 300px;" placeholder="请输入内容"
                        v-model="examComment.comment">
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="submitComment">确 定</el-button>
            </span>
        </el-dialog>

        <el-loading :fullscreen="true" :text="loadingText" :spinner="loadingSpinner" :background="loadingBackground"
            :lock="loadingLock" v-if="loading"></el-loading>
    </div>
</template>
<script>
import {
    findTeacherClassPageList
} from "@/api/classManage/classInfo";
import { queryPage } from "@/api/newExam/plan.js";
import { addOrUpdate, getExamComment } from "@/api/newExam/examComment.js";
import { initExamScoreTable, scoresRecord, exportTemplate, queryList } from "@/api/newExam/scoresRecord.js";
import { getClassAllSubj } from "@/api/baseData/profession.js";
import { getToken } from '@/utils/auth'
export default {
    data() {
        return {
            upload: {
                header: {
                    "Authorization": 'Bearer ' + getToken()
                }
            },
            classOptions: [],
            examOptions: [],
            subjectOptions: [],
            statusOptions: [
                { id: 1, value: '缺考' },
                { id: 0, value: '正常' }
            ],
            examScoreTable: {},
            // 表单校验
            rules: {
                classId: [
                    { required: true, message: "班级不能为空", trigger: "manul" },
                ],
                subjectId: [
                    { required: true, message: "考试科目不能为空", trigger: "manul" },
                ],
                examPlanId: [
                    { required: true, message: "考试计划不能为空", trigger: "manul" },
                ],
                score: [
                    { required: true, message: "请填写成绩", trigger: "blur" },
                ]
            },
            loading: false,
            loadingText: 'Loading',
            loadingSpinner: 'el-icon-loading',
            loadingBackground: 'rgba(0, 0, 0, 0.7)',
            loadingLock: true,
            activeName: 'first',
            fileList: [],
            activeUrl: '',
            limit: 1,
            dialogVisible: false,
            studentScore: [
                { subjectName: '语文', score: 80 },
                { subjectName: '数学', score: 90 },
            ],
            studentName: '',
            examPlanName: '',
            examComment: {},
            dto: {}
        }
    },
    methods: {
        handleClick(tab, event) {
            console.log(tab, event);
        },
        getClassList() {
            //查询班级
            findTeacherClassPageList({
                pageSize: 500,
                pageNum: 1,
                status: 1,
                isGraduation: 0
            }).then(resp => {
                this.classOptions = resp.data.list;
            });
        },
        getExamPlanList() {
            queryPage({ pageSize: 100, pageNum: 1 }).then(resp => {
                this.examOptions = resp.data.list;
            })
        },
        getSubjectList() {
            getClassAllSubj(this.examScoreTable.classId).then(resp => {
                this.subjectOptions = resp.data;
            })
        },
        initTable() {
            const loading = this.$loading({
                lock: true,//lock的修改符--默认是false
                text: 'Loading',//显示在加载图标下方的加载文案
                spinner: 'el-icon-loading',//自定义加载图标类名
                background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
                target: document.querySelector('#table')//loadin覆盖的dom元素节点
            });
            initExamScoreTable(this.examScoreTable).then(resp => {
                this.examScoreTable = resp.data;
                loading.close();
            })
        },
        classChange() {
            // console.log(this.$refs['subjectOption']);
            this.$refs['subjectOption'].resetField()
            if (this.examScoreTable.classId) {
                this.$refs['classOption'].clearValidate()
                this.getSubjectList();
            } else {
                this.examScoreTable.subjectId = null;
                this.subjectOptions = [];
            }
            if (this.examScoreTable.examPlanId && this.examScoreTable.subjectId) {
                this.initTable();
            } else {
                this.examScoreTable.examScoreList = []
            }
        },
        handleChange() {
            this.$forceUpdate()
            if (this.examScoreTable.classId && this.examScoreTable.subjectId && this.examScoreTable.examPlanId) {
                this.initTable();
            } else {
                this.examScoreTable.examScoreList = []
            }
            if (this.examScoreTable.subjectId) {
                this.$refs['subjectOption'].clearValidate()
            }
            if (this.examScoreTable.examPlanId) {
                this.$refs['examPlanOption'].clearValidate()
            }
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,//lock的修改符--默认是false
                        text: 'Loading',//显示在加载图标下方的加载文案
                        spinner: 'el-icon-loading',//自定义加载图标类名
                        background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
                        target: document.querySelector('#table')//loadin覆盖的dom元素节点
                    });
                    scoresRecord(this.examScoreTable).then(resp => {
                        console.log("resp:",resp);
                        loading.close();
                        if (resp.code == '200' && resp.data == '200') {
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            })
                            this.examScoreTable = {};
                        } else {
                            console.log("hhhhhhhh");
                            this.$message({
                                message: resp.message,
                                type: 'error'
                            })
                        }
                    })
                }
            });
        },
        submitUpload() {
            let extention = this.$refs.upload.uploadFiles[0].name;
            let arr = extention.split('.');
            if (arr[1] != 'xls' && arr[1] != 'xlsx') {
                this.$message({
                    message: '只能为xls或xlsx文件！',
                    type: 'error'
                })
                this.fileList = [];
            } else {
                this.$refs.upload.submit().then(resp => {

                });
            }
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleSuccess(resp) {
            console.log("success");
            if (resp.code == '200') {
                this.$message.success('导入成功');
            } else {
                this.$message({
                    message: resp.message,
                    type: 'error'
                })
            }
            this.$refs.upload.clearFiles();
        },
        exportTemp() {
            exportTemplate().then(resp => {
                this.downloadFile(resp.data);
            })
        },
        //文件下载
        downloadFile(data) {
            if (!data) {
                return
            }
            console.log("data:", data);
            const link = document.createElement('a');
            let blob = new Blob([data], {
                type: 'application/vnd.ms-excel'
            });
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);

            link.setAttribute('download', '学生成绩' + '.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        openDialog(row) {
            this.studentName = row.studentName;
            this.examPlanName = this.examScoreTable.examPlanName;
            console.log(this.examScoreTable);
            this.examComment = {};
            this.studentScore = [];
            this.dialogVisible = true;
            this.dto.studentId = row.studentId;
            this.dto.examPlanId = this.examScoreTable.examPlanId;
            this.dto.classId = this.examScoreTable.classId;
            getExamComment(this.dto).then(resp => {
                if (resp.data) {
                    this.examComment = resp.data;
                } else {
                    this.examComment.examPlanId = row.examPlanId;
                    this.examComment.studentId = row.studentId;
                    this.examComment.classId = row.classId;
                }
            })
            queryList(this.dto).then(resp => {
                this.studentScore = resp.data;
            })
        },
        close() {
            this.dialogVisible = false;
        },
        submitComment() {
            addOrUpdate(this.examComment).then(resp => {
                if (resp.code == '200') {
                    this.$message.success('提交成功');
                    this.examComment = {};
                }
                this.close();
            })
        }
    },
    created() {
        this.getClassList();
        this.getExamPlanList();
        this.activeUrl = process.env.VUE_APP_BASE_API + "/examScore/importScore"
    }
}
</script>

<style></style>